Arrange Multiple Graphs on the Same Page
grid.arrange()[in the package gridExtra]
plot_grid() and draw_plot() [in the package cowplot]
Installation error: package ‘cowplot’ is not available (for R version 3.2.3). The R version of my server is.
## _
## platform x86_64-redhat-linux-gnu
## arch x86_64
## os linux-gnu
## system x86_64, linux-gnu
## status
## major 3
## minor 2.3
## year 2015
## month 12
## day 10
## svn rev 69752
## language R
## version.string R version 3.2.3 (2015-12-10)
## nickname Wooden Christmas-Tree
Download cowplot from cran.r-project archive. And intall by source install.packages("~/cowplot_0.6.0.tar.gz", repos = NULL, type = "source").
## Loading required package: gridExtra
##
## Attaching package: 'gridExtra'
## The following object is masked from 'package:dplyr':
##
## combine
data("ToothGrowth")
ToothGrowth$dose <- as.factor(ToothGrowth$dose)
data("economics")
data("diamonds")
my3cols <- c("#E7B800", "#2E9FDF", "#FC4E07")
require(cowplot)
## Loading required package: cowplot
## Warning: `legend.margin` must be specified using `margin()`. For the old
## behavior use legend.spacing
##
## Attaching package: 'cowplot'
## The following object is masked from 'package:ggplot2':
##
## ggsave
p <- ggplot(ToothGrowth, aes(x = dose, y = len))
# boxplot
bxp <- p + geom_boxplot(aes(color = dose)) + scale_color_manual(values = my3cols)
print(bxp)

# Dot plot(dp)
dp <- p + geom_dotplot(aes(color = dose, fill = dose), binaxis = 'y', stackdir = 'center') + scale_color_manual(values = my3cols) + scale_fill_manual(values = my3cols)
print(dp)
## `stat_bindot()` using `bins = 30`. Pick better value with `binwidth`.

# line plot
lp <- ggplot(economics, aes(x = date, y = psavert)) + geom_line(color = '#E46726')
print(lp)

# Default design of cowplot has white background with no grid at all.
# Add gridlines
bxp + background_grid(major = 'xy', minor = 'none')

# Use theme_gray()
bxp + theme_gray()

# Combine multiple plots
# plot_grid(): Combines easily multiple plots
# ggdraw() + draw_plot() + draw_plot_label(): Place graphs at particular locations with a particular sizes.
plot_grid(bxp,dp,lp, labels = c('A','B','C'), ncol=2, nrow = 2)
## `stat_bindot()` using `bins = 30`. Pick better value with `binwidth`.
## Warning: `panel.margin` is deprecated. Please use `panel.spacing` property
## instead

# ggdraw(): Initialize an empty drawing canvas
# draw_plot(): Places a plot somewhere onto the drawing canvas.
# draw_plot_label(): Adds a plot label to the upper left corner of a graph. It can handle vecgors of labels with associated coordinates.
ggdraw() +
draw_plot(bxp, x = 0, y = 0.5, width = 0.5 , height = 0.5) +
draw_plot(dp, x = 0.5, y = 0.5, width = 0.5, height = 0.5) +
draw_plot(lp, x = 0, y = 0, width = 1, height = 0.5) +
draw_plot_label(label = c("A","B","C"), x= c(0, 0.5, 0), y = c(1,1,0.5), size = 15)
## Warning: `panel.margin` is deprecated. Please use `panel.spacing` property
## instead
## `stat_bindot()` using `bins = 30`. Pick better value with `binwidth`.

# Save multi-figure plots
plot2by2 <- plot_grid(bxp,dp,lp, labels = c('A','B','C'), ncol=2, nrow = 2)
## `stat_bindot()` using `bins = 30`. Pick better value with `binwidth`.
## Warning: `panel.margin` is deprecated. Please use `panel.spacing` property
## instead
save_plot('/home/cliu18/liucj/github/RstudioWithGit/practice/Draw_pictures/beautiful_graphics_ggplot2/plot2by2.png', plot2by2, ncol = 2, nrow = 2, base_aspect_ratio = 1.3)
Use gridExtra package.
grid.arrange(): Arrange multiple plots on a page.
my5cols <- c("#6D9EC1", "#646567", "#A29B32", "#E46726", "#F3BF94")
# create a bar plot
data("diamonds")
brp <- ggplot(diamonds, aes(x = clarity)) + geom_bar(aes(fill = cut)) + scale_fill_manual(values = my5cols)
require(gridExtra)
grid.arrange(bxp, dp, lp, brp, ncol = 2, nrow = 2)
## `stat_bindot()` using `bins = 30`. Pick better value with `binwidth`.

grid.arrange() and arrangeGrob(): Change column/row span of a plot.
grid.arrange(bxp, arrangeGrob(dp, brp), ncol = 2)
## `stat_bindot()` using `bins = 30`. Pick better value with `binwidth`.

grid.arrange(brp, bxp, dp, ncol = 2, nrow = 2, layout_matrix = rbind(c(1,1),c(2,3)))
## `stat_bindot()` using `bins = 30`. Pick better value with `binwidth`.

# Use common legend for multiple graphs.
# 1. Get plot legend
get_legend <- function(myggplot){
require(gridExtra)
tmp <- ggplot_gtable(ggplot_build(myggplot))
leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box")
legend <- tmp$grobs[[leg]]
return(legend)
}
# 2. Save the legend from the dot plot
legend <- get_legend(dp)
## `stat_bindot()` using `bins = 30`. Pick better value with `binwidth`.
# 3. Remove the legend from the box plot and the dot plot
bxp2 <- bxp + theme(legend.position = "none")
dp2 <- dp + theme(legend.position = "none")
# 4. Arrange bxp2, dp2 and the legend with a specific width
grid.arrange(bxp2, dp2, legend, ncol = 3, widths = c(2.3,2.3,0.8))
## `stat_bindot()` using `bins = 30`. Pick better value with `binwidth`.

Scatter plot with marginal density plots
set.seed(1234)
x <- c(rnorm(350, mean = -1), rnorm(350, mean = 1.5), rnorm(350, mean = 4))
y <- c(rnorm(350, mean = -0.5), rnorm(350, mean = 1.7), rnorm(350, mean = 2.5))
group <- as.factor(rep(c(1, 2, 3), each = 350))
df2 <- data.frame(x, y, group)
head(df2)
## x y group
## 1 -2.20706575 -0.715413865 1
## 2 -0.72257076 -0.009793331 1
## 3 0.08444118 -0.440606576 1
## 4 -3.34569770 -0.441687947 1
## 5 -0.57087531 1.338363107 1
## 6 -0.49394411 -0.112349101 1
# Scatter plot of x and y variables and color by groups
scatterPlot <- ggplot(df2, aes(x, y)) + geom_point(aes(color = group)) + scale_color_manual(values = my3cols) + theme(legend.position=c(0,1), legend.justification=c(0,1))
# Marginal density plot of x (top panel)
xdensity <- ggplot(df2, aes(x)) + geom_density(aes(fill = group), alpha=.8) + scale_fill_manual(values = my3cols) + theme(legend.position = "none")
# Marginal density plot of y (right panel)
ydensity <- ggplot(df2, aes(y)) + geom_density(aes(fill=group), alpha=.8) + scale_fill_manual(values = my3cols) + theme(legend.position = "none") + coord_flip()
blankPlot <- ggplot()+geom_blank()+ theme_void()
require("gridExtra")
grid.arrange(xdensity, blankPlot, scatterPlot, ydensity, ncol=2, nrow=2, widths=c(4, 1.4), heights=c(1.4, 4))

# ggExtra: Add marginal distributions plots.
require('ggExtra')
## Loading required package: ggExtra

# Marginal histogram plot
ggMarginal(scatterPlot, type = "histogram", fill = "#6D9EC1", color= "#BFD5E3")
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

# Insert an external graphical element inside a ggplot.
# annotation_custom(grob, xmin, xmax, ymin, ymax)
# - grob: the external graphical element to display
# Create a transparent theme object
transparent_theme <- theme(axis.title.x = element_blank(), axis.title.y = element_blank(), axis.text.x = element_blank(), axis.text.y = element_blank(), axis.ticks = element_blank(), panel.grid = element_blank(), axis.line = element_blank(), panel.background = element_rect(fill = "transparent",colour = NA), plot.background = element_rect(fill = "transparent",colour = NA))
p1 <- scatterPlot
# box plot of the x variable
p2 <- ggplot(df2, aes(factor(1),x)) + geom_boxplot(width = 0.3) + coord_flip() + transparent_theme
# box plot of the y variable
p3 <- ggplot(df2, aes(factor(1), y)) + geom_boxplot(width = 0.3) + transparent_theme
# Create the external graphical elements
# called a 'grop' in Grid terminology
p2_grob = ggplotGrob(p2)
p3_grob = ggplotGrob(p3)
# Insert p2_grob inside the scatter plot
xmin <- min(x); xmax <- max(x)
ymin <- min(y); ymax <- max(y)
p1 + annotation_custom(grob = p2_grob, xmin = xmin, xmax = xmax, ymin = ymin - 1.5, ymax = ymin + 1.5)

# Insert p3_grob inside the scatter plot
p1 + annotation_custom(grob = p3_grob, xmin = xmin - 1.5, xmax = xmin + 1.5, ymin = ymin, ymax = ymax)

Correlation Matrix Visualization
GGally and ggcorrplot for displaying a correlation matrix.
Compared to GGally, the ggcorrplot package provides many options for visualizing a correlation matrix.
# Coorelation matrix
require("GGally")
## Loading required package: GGally
## Warning: replacing previous import by 'utils::capture.output' when loading
## 'GGally'
## Warning: replacing previous import by 'utils::head' when loading 'GGally'
## Warning: replacing previous import by 'utils::installed.packages' when
## loading 'GGally'
## Warning: replacing previous import by 'utils::str' when loading 'GGally'
##
## Attaching package: 'GGally'
## The following object is masked from 'package:dplyr':
##
## nasa
mydata <- mtcars[, c(1,3,4,5,6,7)]
ggcorr(mydata, palette = "Set3", label = TRUE)

# Matrix of scatter plot
ggpairs(mydata)

## ggcorrplot
require('ggcorrplot')
## Loading required package: ggcorrplot
mydata <- mtcars[, c(1,3,4,5,6,7)]
corr <- round(cor(mydata),1)
head(corr[,1:6],3)
## mpg disp hp drat wt qsec
## mpg 1.0 -0.8 -0.8 0.7 -0.9 0.4
## disp -0.8 1.0 0.8 -0.7 0.9 -0.4
## hp -0.8 0.8 1.0 -0.4 0.7 -0.7
# Compute a matrix of correlation p-values
p.mat <- cor_pmat(mydata)
head(p.mat[,1:4],3)
## mpg disp hp drat
## mpg 0.000000e+00 9.380327e-10 1.787835e-07 1.776240e-05
## disp 9.380327e-10 0.000000e+00 7.142679e-08 5.282022e-06
## hp 1.787835e-07 7.142679e-08 0.000000e+00 9.988772e-03
# correlation matrix visualization
ggcorrplot(corr)

# reordering the correlation matrix
# use hierarchical clustering
ggcorrplot(corr, hc.order = T, outline.col = "white")

# Types of correlogram layout and customization
# Add correlation coefficients
ggcorrplot(corr, hc.order = T,
type = 'lower',
outline.color = 'white',
ggtheme = ggplot2::theme_bw,
colors = c('#6D9EC1', 'white', '#E46726'),
lab = T)

# Add correlation significance level
# Argument p.mat
# Barring the no significant coefficient
ggcorrplot(corr, hc.order = T, type = 'lower', p.mat = p.mat)
